//
//  gongju.m
//  afn
//
//  Created by mac on 2018/4/13.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "gongju.h"
#import "ZKImgRunLoopView.h"//轮播器
#import "WyzAlbumViewController.h"
@implementation gongju

+(void)AFNPOSTDataUrl:(NSString *)url
               andDic:(NSDictionary *)dic
         andTableView:(UITableView *)tableview
    andViewController:(UIViewController *)viewController
      andSuccessBlock:(void(^)(id responseObject))responseObjectBlock
        anderrorBlock:(void(^)(void))errorBlock{
    
    //如果正在上下拉刷新 就不显示
    if([tableview.mj_header isRefreshing]==NO&&[tableview.mj_footer isRefreshing]==NO)
    {
        
        if(viewController!=nil)
        {
            
            [MBProgressHUD showHUDAddedTo:viewController.view animated:YES];
        }
    }
    
    NSString *request_time=[self NSDateToTimeCuo];
    
    NSMutableDictionary *typeDic2=[NSMutableDictionary dictionaryWithDictionary:dic];
    [typeDic2 setObject:@"ios" forKey:@"is_from"];
    [typeDic2 setObject:request_time forKey:@"request_time"];
    
    NSString *paramsStr;

    NSArray *nameArr = [[typeDic2 allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    for (int i=0; i<nameArr.count; i++) {
        NSString *str=[typeDic2 objectForKey:nameArr[i]];
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

        if (i==0) {
            paramsStr=[NSString stringWithFormat:@"%@=%@",nameArr[i],str];
        }else{
            paramsStr=[NSString stringWithFormat:@"%@&%@=%@",paramsStr,nameArr[i],str];
        }
        
    }
    if ([self charIsNil:paramsStr]) {
        paramsStr=@"";
    }
    
    NSString *sign = [NSString stringWithFormat:@"%@fazhichun",  paramsStr];
    
    
    sign=[sign md5String];
    
    NSMutableDictionary *typeDic=[NSMutableDictionary dictionaryWithDictionary:typeDic2];
    [typeDic setObject:sign forKey:@"sign"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token= [defaults objectForKey:@"token"];
    if (![self charIsNil:token]) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"access-token"];//设置到
    }
    
    [manager POST:[NSString stringWithFormat:@"%@/%@",_addressUrl,url]  parameters:typeDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,typeDic,[[responseObject description] kdtk_stringByReplaceingUnicode]);
            
          
            
            [MBProgressHUD hideHUDForView:viewController.view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
            if (dataModel.code.integerValue==200) {
                if(responseObjectBlock!=nil)
                {
                    
                    responseObjectBlock(dataModel.data);
                }
            }else if (dataModel.code.integerValue==401) {
                [gongju svpInfo:@"登录过时，请先登录"];
                [self ToLoging:viewController];
                return ;
            }
            else{
                [gongju svpInfo:dataModel.message];
                return ;
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:viewController.view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,dic,error);
            
            
            [FTToastIndicator dismiss];
            
            [gongju svpInfo:@"网络连接失败"];
            
            if(errorBlock!=nil)
            {
                errorBlock();
            }
            
        });
    }];
    
}

+(void)AFNGETDataUrl:(NSString *)url
              andDic:(NSDictionary *)dic
        andTableView:(UITableView *)tableview
             andView:(UIView *)view
     andSuccessBlock:(void(^)(id responseObject))responseObjectBlock
       anderrorBlock:(void(^)(void))errorBlock{
    
    //如果正在上下拉刷新 就不显示
    if([tableview.mj_header isRefreshing]==NO&&[tableview.mj_footer isRefreshing]==NO)
    {
        
        if(view!=nil)
        {
            
            [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
    }
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    [manager GET:[NSString stringWithFormat:@"%@/%@",_addressUrl,url]  parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,dic,[[responseObject description] kdtk_stringByReplaceingUnicode]);
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
            if (dataModel.code.integerValue==200) {
                if(responseObjectBlock!=nil)
                {
                    
                    responseObjectBlock(dataModel.data);
                }
            }
            else{
                [gongju svpInfo:dataModel.message];
                return ;
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,dic,error);
            
            
            [FTToastIndicator dismiss];
            
            [gongju svpInfo:@"网络连接失败"];
            
            if(errorBlock!=nil)
            {
                errorBlock();
            }
            
        });
    }];
}


+ (void)getHederImage :(UIViewContentMode )contentMode :(CGRect)rect :(NSArray*)imageUrlArr :(CGFloat)fenYeheight :(UIView *)rootView :(void(^)(int value)) block
{
    
    //网络图片happendTime
    //网络图片
    
    
    
    
    ZKImgRunLoopView *imgRunView = [[ZKImgRunLoopView alloc] initWithFrame:rect fenYeheight:fenYeheight placeholderImg:_zhanweiImageData];
    imgRunView.imgUrlArray =imageUrlArr;
    [rootView addSubview:imgRunView];
    
    imgRunView.contentMode=contentMode;
    [imgRunView  touchImageIndexBlock:^(NSInteger index) {
        
        if(block!=nil)
        {
            block((int)index);
        }
    }];
    
}
+(void)LookBigPicture:(NSInteger)index imageArr:(NSArray *)imageArr imageNameArray:(NSArray *)imageNameArray viewController:(UIViewController *)viewController{
    
    WyzAlbumViewController *wyzAlbumVC = [[WyzAlbumViewController alloc]init];
    
    wyzAlbumVC.currentIndex =index;//这个参数表示当前图片的index，默认是0
    
    //图片数组，可以是url，也可以是UIImage
    //第一种用url
    wyzAlbumVC.imgArr = imageArr;
    wyzAlbumVC.imageNameArray=imageNameArray;//图片名字数组可以为空
    //进入动画
    
    [viewController presentViewController:wyzAlbumVC animated:YES completion:nil];
}

#pragma mark————————svp提醒
+ (void)svpInfo:(NSString *)title
{
    Toast *toast = [Toast toast]; //创建一个toast
    [toast makeText:title]; //显示
}

+(NSString*)encodeString:(NSString*)unencodedString{
    
    NSString *str=@"";
    NSArray *array = [unencodedString componentsSeparatedByString:@" "];
    for (int i=0;i<array.count; i++) {
        if (i==0) {
            str= [array[i] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        else{
            str=[NSString stringWithFormat:@"%@+%@",str,[array[i]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    return str;
}

//判断字符是否为空
+(BOOL)charIsNil:(NSString *)str{
    
    if ([str isKindOfClass:[NSNull class]]||[str isEqualToString:@""]||str==nil) {
        return YES;
    }
    return  NO;
}

#pragma mark————————————————得到当前时间搓 转 时间搓
+ (NSString *)NSDateToTimeCuo
{
    
    NSDate *date=[NSDate new];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    
    return timeSp;
}
#pragma mark———————————————— 计算文字宽度
+ (CGSize)getNSStringWeight:(NSString *)string andViewWight:(CGFloat)height andFont:(NSInteger)font
{
    
    
    return  [string sizeOfTextWithMaxSize:CGSizeMake(MAXFLOAT, height) font:[UIFont systemFontOfSize:font]];
    
}

#pragma mark———————————————— 计算文字高度
+ (CGSize)getNSStringSize:(NSString *)string andViewWight:(CGFloat)weight andFont:(NSInteger)font
{
    
    
    return  [string sizeOfTextWithMaxSize:CGSizeMake(weight, MAXFLOAT) font:[UIFont systemFontOfSize:font]];
    
}
#pragma mark———————————————— 跳转 push
+ (void)pushNextViewController:(UIViewController *)nextViewController andRootController:(UIViewController *)rootVc
{
    
    
    rootVc.hidesBottomBarWhenPushed = YES;
    
    [nextViewController.navigationController pushViewController:rootVc
                                                       animated:YES];
    
}

#pragma mark———————————————— 验证手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobileNum];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobileNum];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobileNum];
    
    if (isMatch1 || isMatch2 || isMatch3) {
        return YES;
    }else{
        return NO;
    }
}

+(void)ToLoging:(UIViewController *)controller{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你还未登录请前往登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleDefault   handler:nil];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault  handler:^(UIAlertAction * action) {
        _loginWithVc(controller);
    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [controller presentViewController:alert animated:YES completion:nil];
}

@end
